/*
 * Drunk Js
 * Author    :   Drunk
 * Website   :   http://drunkce.com,  http://idrunk.net
 */

Drunk.cookiePrefix = "D_" ;

dce = {
    filter : function(){
        var form = $('form.filter:first');
        if(!form.length)return ;

        form.bind('submit', function(){
            var action = form.attr('action'),
                elem, elemval, ename, elem_parsed, vice_parament, k , type , vice, url,
                elems = form.find('[name]').not('[name^=__]'),
                config = [], main_elems = {}, vice_elems = {};
            elems.each(function(i, e){
                elem = $(e);
                ename = elem.attr('name');
                elem_parsed = ename.Split('-');
                vice_parament = ename.Split(':');
                if(elem_parsed.length > 1) main_elems[elem_parsed[1]] = [elem_parsed[0], elem_parsed[1], elem];
                if(vice_parament.length > 1) vice_elems[vice_parament[0]] = elem;
            });
            for(k in main_elems){
                elem = main_elems[k][2];
                type = main_elems[k][0];
                elemval = elem.val();
                vice = vice_elems[k] ? vice_elems[k].is(':checked') : false;
                if(type == 'category'){
                    config[config.length] = '1' + k + '~*' + elemval;
                }else if(type == 'status'){
                    if(!D.empty(elemval)) config[config.length] = '1' + k + '&' + elemval +','+ (vice ? 0 : elemval);
                }else if(type == 'selecter' || type === 'linkage' || type === 'autocomplete'){
                    if(elemval != '' && elemval != '0') config[config.length] = '1' + k + '=' + elemval;
                }else if(type == 'section'){
                    var elemFrom = form.find('[name="' +k+':from"]'),
                        elemTo = form.find('[name="' +k+ ':to"]');
                    if(!DC.code(elemFrom, 1) && !DC.code(elemTo, 1)){
                        config[config.length] = '1' + k + '-' + elemFrom.val() + ',' + elemTo.val();
                    }else if(!DC.code(elemFrom, 1)){
                        config[config.length] = '1' + k + '>=' + elemFrom.val();
                    }else if(!DC.code(elemTo, 1)){
                        config[config.length] = '1' + k + '<=' + elemTo.val();
                    }
                }else{
                    config[config.length] = '1' + k + '*~*' + elemval;
                }
            }
            querys = config.join(';');
            url = action.replace(/!search/i, encodeURIComponent(querys).spechar(2));
            $.isFunction(window.searchCall) ? searchCall.call(this, url) : location.href = url;
            return false;
        });
    }
};

logform = {
    config : {jump : 1} ,
    loadvarscript : function(callback){
        if(typeof variable !== "undefined")return callback && callback() ;
        D.loadScript('/public/component/drunk/extends/variable.js','',callback) ;
    } ,
    dialog : function(config){
        if(logform.loginfo())return false ;
        var form = '<form method="post" action="/index.php/86-druson~1.html"><table><tr><th>帐号：</th><td><input name="account" class="input" drunk="input=#999,用户名" autocomplete="off" /></td></tr>' +
            '<tr><th>密码：</th><td><input type="password" class="input" name="password" drunk="input=#999,8888888888" /></td></tr>' +
            '<tr><th>验证码：</th><td><input name="verify_login" class="input" drunk="variable=verify,\'{ w:80,h:24,c:4}\',;input=#999,验证码" autocomplete="off" /></td></tr>' +
            '<tr><th>&nbsp;</th><td><input type="submit" class="button" value="登录" /> <a class="reg" target="_blank" href="/index.php/reg.html">注册</a><input type="button" class="button cancel" value="取消" /></td></tr>' +
            '</table></form>' ;

        Drunk.extend(logform.config, config) ;
        var dialog = logform.yo()($(form)) ;
        logform.title("会员登录") ;
        dialog.find('form').bind('submit', logform.submit) ;
        dialog.find('input.cancel').bind('click', logform.destroy) ;
        D(function(){DC.init(dialog) ;}) ;
    } ,
    submit : function(){
        var elem , f = $(this),
            action = f.prop('action'),
            json = {},
            elems = f.find('input[name]');

        elems.each(function(i,e){
            elem = $(e);
            json[elem.prop('name')] = elem.val();
        }) ;

        $.ajax({
            type:'POST',
            url:action,
            data:json,
            dataType:"json",
            success : function(data){
                if(!data || !data.status){
                    if(data)logform.notice(data.message, 5000) ;
                    return logform.verifyRefresh() ;
                }
                if(logform.config.jump && data.jump)location.href = data.jump ;
                logform.notice(data.message, 2000, 0, 'success', logform.destroy) ;
            }
        }) ;

        return false ;
    } ,
    title : function(title){logform.body().find('.form_title span').html(title) ;} ,
    notice : function(string, timeout, selecter, className, callback){
        var notice = $('#' + logform.loginFormId + ' div.notice').remove() ;
        notice = $('<div class="notice '+(className || '')+'">'+string+'</div>') ;
        if(selecter){
            $(selecter).append(notice) ;
        }else{logform.yo()(notice, 1) ;}
        var noticeHeight = notice.height() ;
        notice.height(0).hide() ;
        window.setTimeout(function(){notice.animate({'height':noticeHeight + 'px','opacity':'show'}, 'fast', 'swing');}, 1) ;
        var autoHide = function(){notice.animate({'height':0,'opacity':'hide'}, 'slow', 'swing', callback);} ;
        if(timeout && timeout > 0)window.setTimeout(autoHide, timeout) ;
        return false ;
    } ,
    verifyRefresh : function(){logform.yo()().find('img').trigger('click') ;} ,
    body : function(){return $('#' + logform.loginFormId);},
    loginFormId : 'justaloginformyo' ,
    yo : function(config){
        config = $.isPlainObject(config) ? config : {} ;
        var dialog = $('#' + logform.loginFormId) ,
            win = $(window),
            fwidth = config.width || 500, fheight = config.height || 350, winWidth = win.width(), winHeight = win.height() ,
            fleft = (winWidth - fwidth) / 2, ftop = (winHeight - fheight) / 2 ,
            borderWidth = config.borderWidth || 12, bgWidth = fwidth - borderWidth * 2 , bgHeight = fheight - borderWidth * 2 ,
            titleHeight = config.titleHeight || 36, bodyHeight = bgHeight - titleHeight ;
        if(D.browser.msie && D.browser.ver == 6)ftop += win.scrollTop();

        if(!dialog.length){
            dialog = '<div id="'+logform.loginFormId+'"><div class="form_bg"></div>'+ (D.browser.msie && D.browser.ver == 6 ? '&nbsp;' : '') +'<div class="form_title"><span></span><em>X</em></div><div class="form_body"></div></div>' ;
            var css = '<style type="text/css">#'+logform.loginFormId+'{position:fixed;_position:absolute;z-index:9999;}\n' +
                '#'+logform.loginFormId+' .form_bg{position:absolute;background-color:#000;width:100%;height:100%;z-index:-1;opacity:0.2;filter:alpha(opacity=20)\9;}\n' +
                '#'+logform.loginFormId+' .form_title{background-color:#fff;padding:0 10px;position:relative;}\n' +
                '#'+logform.loginFormId+' .form_body{color:#333;background-color:#fff;padding:0 5px;position:relative;}\n' +
                '#'+logform.loginFormId+' .form_title span{color:#333;font-size:14px;font-weight:bold;}\n' +
                '#'+logform.loginFormId+' .form_title em{font-family:Arial;display:inline-block;*display:inline;*zoom:1;position:absolute;top:5px;right:6px;width:18px;height:18px;line-height:18px;'+
                'text-align:center;border:1px solid #ccc;color:#666;cursor:pointer;border-radius:3px;}\n' +
                '#'+logform.loginFormId+' .form_title em:hover{color:#fff;background-color:#999;border-color:#888;}\n'+
                '#'+logform.loginFormId+' .form_body .notice{color:#f00;height:30px;border-radius:6px;border:1px solid #f99;line-height:30px;padding-left:26%;background-color:#eee;}\n'+
                '#'+logform.loginFormId+' .form_body .notice.success{color:#063;border-color:#096;}\n'+
                '#'+logform.loginFormId+' th,#'+logform.loginFormId+' td{padding:7px 5px;}\n' +
                '#'+logform.loginFormId+' th{font-weight:400;text-align:right;width:25%;font-size:12px;}\n' +
                '#'+logform.loginFormId+' th em{color:red;}\n' +
                '#'+logform.loginFormId+' td *{vertical-align:middle;}\n' +
                '#'+logform.loginFormId+' form{padding-top:5px;}\n' +
                '#'+logform.loginFormId+' form input.input{border:1px solid #666;width:200px;height:22px;line-height:22px;}\n' +
                '#'+logform.loginFormId+' form a{color:#000;}\n' +
                '#'+logform.loginFormId+' form textarea{border:1px solid #666;width:280px;height:70px;}</style>' ;
            logform.loadvarscript() ;
            dialog = $(dialog).appendTo(document.body).hide().after(css) ;
            dialog.find('.form_title em').bind('click', logform.destroy) ;
        }
        dialog.find('.form_title').css({margin:(D.browser.msie && D.browser.ver == 6 ? '-3' : borderWidth)+'px '+borderWidth+'px 0', height:titleHeight+'px', lineHeight:titleHeight+'px'}) ;
        dialog.find('.form_body').css({margin:'0 '+borderWidth+'px '+borderWidth+'px', height:bodyHeight+'px'}) ;

        return function(form, method){
            if(Drunk.isElem(form, 0, 1)){
                var form_body = dialog.animate({'opacity':'show', 'width':fwidth+'px', 'height':fheight+'px', 'left':fleft+'px', 'top':ftop+'px'}, 'slow', 'swing').find(".form_body") ;
                if(!(method & 1))form_body.empty() ;
                form_body.prepend(form) ;
            }
            return dialog ;
        }
    } ,
    loauth : function(cid){
        var config = {width : 700, height : 500},
            url = '/index.php?s=/loauth-' + cid,
            form = '<iframe src="' +url+ '" frameborder="0" scrolling="no" width="100%" height="100%"></iframe>' ;

        var dialog = logform.yo(config)($(form)) ;
        logform.title({0:"QQ登录",1:"微博登录"}[cid]) ;
    },
    destroy : function(){
        callback = $.isFunction(logform.config.cancel) ? logform.config.cancel : $.noop() ;
        logform.body().animate({'opacity':'hide'}, 'swing', callback).find('iframe').attr('src', 'about:blank') ;
    } ,
    loginfo : function(){return D.cookie('member') ;} ,
    init : function(){
        var tmpfunc = function(evt){
            logform.loauth(evt.data.cid);
            return false;
        }
        $('.qq_login').bind('click', {'cid':0}, tmpfunc);
        $('.weibo_login').bind('click', {'cid':1}, tmpfunc);
    },
    message : function(){
        if(!logform.loginfo())return ;
        var url = '/index.php/message_get.html' ;
        $.ajax({
            type:'POST',
            url:url,
            dataType:"json",
            success:function(data){
                if(D.empty(data))return ;
                if(data.info && $.isPlainObject(data.info.message) && data.info.message.message){
                    var message = data.info.message, data = [] , i = 0 , msg ;
                    for(i;i<message.message.length;i++){
                        msg = message.message[i] ;
                        data[data.length] = {'target':'_blank', 'text':'['+ msg[1] +'] '+ msg[3] +' '+ msg[2], href:message.url + '#id=' + msg[0]} ;
                    }
                    $('.managerdoor:first').append('<em>('+message.message.length+')</em>').extenu(data) ;
                }
            }
        }) ;
    }
} ;

$(function(){
    dce.filter();
})

jQuery.fn.extend({
	// method		{1:auto trigger, 2:don't auto hide, 4:remove item, 8:insert item, 16:replace item}
	// 	extend {128:just a panel, 32:set item class, 64:hide}
	extenu : function(c, method, start, length){
		var elem, _elem = this , body = $(document.body), win = $(window),
            c = $.isPlainObject(c) ? c : {items : c},
            data = c.items;
		var call = {
			build : function(e, elem, start, length){
				if(!(method & 128))data = $.isArray(data) ? data : [data] ;
				var ul, li, a, target, insertAfter ;
				
				if(!e._menu){
					var child = method & 128 ? data : $('<ul>');
					if(method & 32)e._class = start && !D.isInt(start) ? start : 'hover';
                    e.c = c;
                    if($.isFunction(c.blurcall)) e.blurcall = c.blurcall;
					e._menu = $('<div class="extenu">').append(child).appendTo(body) ;
                    if(c.class_menu) e._menu.addClass(c.class_menu);
					e._menu.bind('mouseover', {e:e}, call.menuover).bind('mouseout', {e:e}, call.menuout).hide() ;
					elem.bind('mouseover focus', {e:e, elem:elem}, call.over) ;
					if(!(method & 2))elem.bind('mouseout blur', {e:e, elem:elem}, call.out) ;
					if(method & 1)elem.trigger('mouseover') ;
				}
				if(method & 128)return;

				ul = e._menu.children('ul') ;
				if(method & 24){
					var lis = ul.children('li') ,
						lilen = lis.length ;
					length = D.int(length) ;
					if(D.isInt(start)){
						if(start < 0)start = 0 ;
					}else{
						start = lis.has(start).index() ;
						if(start < 0)return ;
					}
					if(!length && (method & 16))length = lilen - start ;
					if(start < lilen - 1)insertAfter = lis.eq(start) ;
				}
				for(var i=0;i<data.length;i++){
					if(D.empty(data[i]))continue ;
					li = $('<li>') ;
					if($.isPlainObject(data[i])){
						target = data[i].target ? ' target="'+data[i].target+'"' : '' ;
						a = $('<a href="'+data[i].href+'"'+target+'>'+data[i].text+'</a>').appendTo(li) ;
						if($.isFunction(data[i]['click']))a.bind('click', {data:data, i:i}, data[i]['click']) ;
					}else{
						li.append(data[i]) ;
					}
					insertAfter ? li.insertBefore(insertAfter) : li.appendTo(ul) ;
				}
				if((method & 16) && insertAfter)call.remove(e, insertAfter.index(), length) ;
			} ,
			remove : function(e, start, length){
				if(!e._menu)return ;
				var lis = e._menu.find('>ul>li') ;
				if(!length){
					length = start || 1 ;
					if(!D.isInt(data))data = lis.has(data).index() ;
					start = D.int(data) ;
					if(start < 0)return false ;
				}
				for(var i=length-1;i>=0;i--)lis.eq(start + i).remove() ;
			} ,
			over : function(evt){
				if(!D.isTriggered(this))return ;
				var e = evt.data.e ,
					elem = evt.data.elem ,
					offset = elem.offset() ,
					size = {width:elem.width(), height:elem.height()} ,
					winsize = {width:win.width(), height:win.height() + $(document).scrollTop()} ,
					_offset = {left:offset.left, top:offset.top + size.height} ,
					menusize = {width:e._menu.outerWidth(true),height:e._menu.outerHeight(true)} ;

				call.hover(e, 1);
                if(e.c.align === 'right') _offset.left = offset.left + size.width - menusize.width;
				if(menusize.width + _offset.left > winsize.width)_offset.left = winsize.width - menusize.width ;
				if(menusize.height + _offset.top > winsize.height)_offset.top = offset.top - menusize.height ;
				e._menu.offset(_offset) ;
			} ,
			out : function(e){
				if(!D.isTriggered(this))return ;
				e.data.e.timerOfHide = window.setTimeout(function(){call.hover(e.data.e);}, 200) ;
			} ,
			menuover : function(e){
				if(!D.isTriggered(this))return ;
				window.clearTimeout(e.data.e.timerOfHide) ;
			} ,
			menuout : function(e){
				if(!D.isTriggered(this))return ;
                if($.isFunction(e.data.e.blurcall)) e.data.e.blurcall.call(e);
				call.hover(e.data.e);
			} ,
			hover : function(e, flag){
				if(flag){
					e._menu.show();
					if(e._class)$(e).addClass(e._class);
				}else{
					e._menu.hide();
					if(e._class)$(e).removeClass(e._class);
				}
			}
		} ;

		$._extenuCss() ;
		_elem.each(function(i, e){
			if(method & 64){
				call.hover(e);
			}else if(method & 4){
				call.remove(e, start, length) ;
			}else{
				call.build(e, _elem.eq(i), start, length) ;
			}
		}) ;
		return _elem ;
	},
	flash : function(count, duration, bgcolor) {
		var elem = this,
			count = (count || 3) * 2 ,
			duration = duration || 120 ,
			bgcolor = bgcolor || "#EABBBB" ,
			flashColor = [elem.css("background-color"), bgcolor] ,
			i = 1;

		for(;i<=count;i++){
			(function(i){
				window.setTimeout(function(){
					elem.css({backgroundColor: flashColor[i % 2]}) ;
					if(i == count)elem.trigger('focus') ;
				}, duration * i)
			})(i) ;
		}
		return elem ;
	}
}) ;
jQuery.extend({
	_extenuCss : function(){
		if($('style[title=extenu]').length)return ;
		$(document.body).append('<style title="extenu" type="text/css">' +
			'.extenu{z-index:9999;position:absolute;background:#fff;padding:5px 0;border:1px solid #ccc;box-shadow:0 1px 0 rgba(0,0,0,0.08),inset 0 1px 2px rgba(255,255,255,0.75);text-shadow: 0 1px 0 rgb(240,240,240);font-size:12px;}' +
			'.extenu li,.extenu li a{height:24px;line-height:24px;padding:0 10px;color:#303942;overflow:hidden;}' +
			'.extenu li a{display:block;padding:0;}' +
			'.extenu li:hover,.extenu li a:hover{background:#eee;}'+
			'.panel_extenu{padding:0 5px;}'+
			'.panel_extenu div.notice{padding-top:5px;display:none;}'+
			'.panel_extenu div.control{padding-top:5px;}</style>') ;
	}
});